package kr.hyunist.androidcomplete02saeildamil.ch25;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import kr.hyunist.androidcomplete02saeildamil.R;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

public class FIleIOTest extends Activity {
	EditText mEdit;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.fileio);
		
		mEdit = (EditText) findViewById(R.id.fileiotestet);
	}
	
	public void mOnClick(View v){
		switch(v.getId()){
		case R.id.fileiotestsave:
			try {
				FileOutputStream fos = openFileOutput("test.txt", Context.MODE_WORLD_READABLE);
				String str = mEdit.getText().toString();
				fos.write(str.getBytes());
				fos.close();
				mEdit.setText("Write Success!");
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			break;
		
		case R.id.fileiotestload:
			try {
				FileInputStream fis = openFileInput("test.txt");
				byte[] data = new byte[fis.available()];
				while(fis.read(data) != -1){
					;
				}
				fis.close();
				mEdit.setText(new String(data));
			} catch (FileNotFoundException e) {
				mEdit.setText("File Not Found");
			} catch (IOException e) {
				e.printStackTrace();
			}
			break;
		
		
		case R.id.fileiotestloadres:
			try {
				InputStream fres = getResources().openRawResource(R.raw.restext);
				byte[] data = new byte[fres.available()];
				while(fres.read(data) != -1){
					
				}
				fres.close();
				mEdit.setText(new String(data));
			} catch(Exception e) {
				
			}
			break;
			
		case R.id.fileiotestdelete:
			if(deleteFile("test.txt")){
				mEdit.setText("delete success!");
			} else {
				mEdit.setText("delete failed!");
			}
			break;
		}
	}
}
